//
//  AIWebViewController.m
//  AssetsInventory
//
//  Created by 李沛池 on 2017/11/16.
//  Copyright © 2017年 李沛池. All rights reserved.
//

#import "AIWebViewController.h"
#import <LPCDefine.h>
#import "WebViewJavascriptBridge.h"
#import "AITools.h"
#import "SGQRCodeView.h"
#import <LPCMBProgressHUD.h>
#import "LPCSVProgressHUD.h"

//t7790413 123456
//00943761 123456
//50423497 123456

//com.godlike.assetsInventory
//com.emp.assetsinventory
//petrochina.jdyt.zcpd

//#define TYPE_Local 1 //是否使用本地html测试模式
//#define URL_WebView    @"http://zhengb.com.cn/test/webview/#/home"
//#define URL_WebView    @"http://lhsm.weiapp.pw:3575/AssetsDataPhone/inventory-master/index.html"
//#define URL_WebView    @"http://122.112.243.143/test/inventory-master/index.html"
//#define URL_WebView    @"http://123.206.49.233" //大熊服务器
//#define URL_WebView    @"http://10.193.142.112:8080/EquipmentManager/inventory-master/index.html"
//#define URL_WebView    @"http://210.12.194.218:9080/AssetsDataPhone/inventory-master/index.html"
//#define URL_WebView    @"http://10.86.14.65:10390/AssetsDataPhone/inventory-master/index.html"
//#define URL_WebView    @"http://127.0.0.1:10390/AssetsDataPhone/inventory-master/index.html"
//#define URL_WebView    @"http://127.0.0.1:10401/AssetsDataPhone/inventory-master/index.html"
//#define URL_WebView    @"http://127.0.0.1:5500/index.html" //本地服务器
#define URL_WebView    @"http://192.168.6.190/inventory-master/index.html" //本地服务器

//本地保存的文件目录
#define PATH_Document           [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
//基于单位编号区分文件读写路径
#define PATH_Depart             [PATH_Document stringByAppendingPathComponent:[self getCurrentDepartcode]]
//下载文件存储目录
#define PATH_DownloadPath       [PATH_Depart stringByAppendingPathComponent:@"AIDownloadFile"]
//本地保存的文件目录
#define PATH_LocalSavePath      [PATH_Depart stringByAppendingPathComponent:@"AILocalSaveFile"]
//待提交的文件路径
#define PATH_TobesubmitListPath [PATH_LocalSavePath stringByAppendingPathComponent:@"tobesubmitList"]
//报废资产的文件路径
#define PATH_ScrapListPath      [PATH_LocalSavePath stringByAppendingPathComponent:@"scrapList"]
//单位表路径
#define PATH_DepartsPath        [PATH_LocalSavePath stringByAppendingPathComponent:@"InvoiceDeparts.json"]
//存放地点字典路径
#define PATH_CFDD               [PATH_LocalSavePath stringByAppendingPathComponent:@"CFDD.json"]
//盘盈原因字典
#define PATH_PYYY               [PATH_LocalSavePath stringByAppendingPathComponent:@"PYYY.json"]
//单位列表的文件路径
#define PATH_DepartListPath     [PATH_LocalSavePath stringByAppendingPathComponent:@"departList"]
#define PATH_DepartListPath2    [PATH_LocalSavePath stringByAppendingPathComponent:@"departList2"]
//Zjb
#define PATH_ZjbListPath        [PATH_LocalSavePath stringByAppendingPathComponent:@"ZjbList"]

@interface AIWebViewController ()<
WKUIDelegate,
WKNavigationDelegate>

@end

@implementation AIWebViewController
{
    WKWebView *_webView;
    WebViewJavascriptBridge* _bridge;
    WVJBResponseCallback _callback;
}

- (void)dealloc
{
    [_webView setNavigationDelegate:nil];
    [_webView setUIDelegate:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initUI];
    
//    UIInterpolatingMotionEffect *interpolationHorizontal = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.x" type:UIInterpolatingMotionEffectTypeTiltAlongHorizontalAxis];
//    interpolationHorizontal.minimumRelativeValue = @(-SCREEN_WIDTH);
//    interpolationHorizontal.maximumRelativeValue = @(SCREEN_WIDTH);
//
//    UIInterpolatingMotionEffect *interpolationVertical = [[UIInterpolatingMotionEffect alloc] initWithKeyPath:@"center.y" type:UIInterpolatingMotionEffectTypeTiltAlongVerticalAxis];
//    interpolationVertical.minimumRelativeValue = @(-SCREEN_HEIGHT);
//    interpolationVertical.maximumRelativeValue = @(SCREEN_HEIGHT);
//
//    [self.view addMotionEffect:interpolationHorizontal];
//    [self.view addMotionEffect:interpolationVertical];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//    [self saveTobesubmitArray:@{@"key":@"value"}];
//    NSString *str = [self getJSONWithDeviceId:@(170923024433530)];
//    NSArray *array = [self fileNamesArrayAtDownload];
}

- (void)viewDidDisappear:(BOOL)animated
{
//    [super viewDidDisappear:animated];
    
//    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60]];
}

- (void)initUI
{
    [self initWebView];
    [self initBridge];
}

- (void)initWebView
{
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    [self.view addSubview:_webView];
}

//初始化  WebViewJavascriptBridge
- (void)initBridge
{
    if (_bridge) { return; }
    [WebViewJavascriptBridge enableLogging];
    _bridge = [WebViewJavascriptBridge bridgeForWebView:_webView];
    [_bridge setWebViewDelegate:self];
    
#ifdef TYPE_Local
    //本地端html
    NSString* htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];      
    NSString* appHtml = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
    NSURL *baseURL = [NSURL fileURLWithPath:htmlPath];
    [_webView loadHTMLString:appHtml baseURL:baseURL];
#else
    NSURLRequestCachePolicy cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
    if (![AITools networkStatus]) {
        cachePolicy = NSURLRequestReturnCacheDataDontLoad;
    }
    //获取保存在本地的服务器配置信息
    NSArray *arrayServerConfig = [AITools jsonStringToObject:[self getCurrentServerConfig]];
    //默认URL
    NSString *strURL = URL_WebView;
    //如果本地有保存的服务器配置信息则使用本地配置的
    if (arrayServerConfig && arrayServerConfig.count > 3) {
//        strURL = [NSString stringWithFormat:@"%@://%@:%@/%@/inventory-master/index.html",arrayServerConfig[0],arrayServerConfig[1],arrayServerConfig[2],arrayServerConfig[3]];
    }
    //网络端html
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:strURL] cachePolicy:cachePolicy timeoutInterval:60]];
    
//    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL_WebView] cachePolicy:cachePolicy timeoutInterval:60]];
#endif
    //注册JS回调方法
    [self registerJSHandler];
}


#pragma mark - JS调用的方法
- (void)registerJSHandler
{
    //显示进度浮窗
    [_bridge registerHandler:@"onShowProgress" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self showProgress:data]));
    }];
    
    //隐藏进度浮窗
    [_bridge registerHandler:@"onHideProgress" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self hideProgress]));
    }];
    
    //保存登陆信息
    [_bridge registerHandler:@"onLoginInfo" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveLoginJSON:data]));
    }];
    
    //获取登陆信息
    [_bridge registerHandler:@"onGetLoginJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getLoginJSON]);
    }];
    
    //查询本地已存在的文件数组
    [_bridge registerHandler:@"fileNamesArray" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self fileNamesArrayAtDownload]);
    }];
    
    //查询本地已存在的必要资产数组
    [_bridge registerHandler:@"onGetNecessaryJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self onGetNecessaryJSONAtDownload]);
//        responseCallback([self fileDataArrayAtDownload]);
    }];
    
    //根据plNum查询计划书中的的资产数组
    [_bridge registerHandler:@"onGetFileListByPlNum" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self fileDataArrayAtDownloadFile:data]);
    }];
    
    //保存单个公司的盘点详细数据
    [_bridge registerHandler:@"saveDetailJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
//        [self saveNecessaryDetailJSON:data handler:responseCallback];
        [self saveDetailJSON:data handler:responseCallback];
    }];
    
    //保存单位列表
    [_bridge registerHandler:@"onSaveAllDepartsJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveDepartList:data]));
    }];
    
    //获取单位列表
    [_bridge registerHandler:@"onGetDepartsJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getDepartList]);
    }];
    
    //保存单位列表2
    [_bridge registerHandler:@"onSaveAllDepartsJSON2" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveDepartList2:data]));
    }];
    
    //获取单位列表2
    [_bridge registerHandler:@"onGetDepartsJSON2" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getDepartList2]);
    }];
    
    //保存单个公司的必要盘点数据
    [_bridge registerHandler:@"onSaveNecessaryJSON" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        [self saveNecessaryDetailJSON:data handler:responseCallback];
    }];
    
    //扫描二维码
    [_bridge registerHandler:@"scanQR_AI" handler:^(id data, WVJBResponseCallback responseCallback) {
        //调用二维码扫描页面
        [SGQRCodeView showScanWithCallBack:^(NSString *str) {
            responseCallback([self getJSONWithDeviceId:str]);
        }];
    }];
    
    //根据id查询指定设备的详细数据
    [_bridge registerHandler:@"getJSONWithDeviceId" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getJSONWithDeviceId:data]);
    }];
    [_bridge registerHandler:@"onGetDeviceById" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getJSONWithDeviceId:data]);
    }];
    
    //获取待提交的盘点申请列表
    [_bridge registerHandler:@"getTobesubmitArray" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getTobesubmitArray]);
    }];
    
    //获取待提交的盘点申请单位列表
    [_bridge registerHandler:@"onGetTobesubmitDepartArray" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getTobesubmitDepartArray]);
    }];
    
    //保存待提交的盘点申请到本地
    [_bridge registerHandler:@"saveTobesubmit" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveTobesubmitArray:data]));
    }];
    
    //删除对应的待提交盘点数据
    [_bridge registerHandler:@"onUnStashDeviceList" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (data) {
            [self deleteTobesubmitWithBarcode:data];
        }
    }];
    
    //清空待提交的盘点申请列表
    [_bridge registerHandler:@"cleanTobesubmit" handler:^(id data, WVJBResponseCallback responseCallback) {
        if (data) {
            [self cleanTobesubmit];
        }
    }];
    
    //保存报废列表
    [_bridge registerHandler:@"onSaveScrapList" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveScrapList:data]));
    }];
    
    //将报废信息加入报废列表
    [_bridge registerHandler:@"onAddToScrapList" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self addToScrapList:data]));
    }];
    
    //删除报废列表中的一部分
    [_bridge registerHandler:@"onRemoveItemOfScrapList" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self removeItemOfScrapList:data]));
    }];
    
    //获取报废列表
    [_bridge registerHandler:@"onGetScrapList" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getScrapList]);
    }];
    
    //清除报废列表
    [_bridge registerHandler:@"onClearScrapList" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self clearScrapList]));
    }];
    
    //根据departCode获取设备列表
    [_bridge registerHandler:@"onFindDevicesByDepartCode" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self findDevicesByDepartCode:data]);
    }];
    
    //保存覆盖新的单位列表
    [_bridge registerHandler:@"onSaveDeparts" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self onSaveDeparts:data]));
    }];
    
    //获取调入单位
    [_bridge registerHandler:@"onGetSetInDeparts" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getSetInDeparts:data]);
    }];
    
    //获取调出单位
    [_bridge registerHandler:@"onGetSetOutDeparts" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getSetOutDeparts]);
    }];
    
    //保存覆盖新的存放地点
    [_bridge registerHandler:@"onSaveCFDD" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self onSaveCFDD:data]));
    }];
    
    //获取存放地点
    [_bridge registerHandler:@"onGetCFDD" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getCFDDDic]);
    }];
    
    //保存覆盖新的盘盈原因
    [_bridge registerHandler:@"onSavePYYY" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self onSavePYYY:data]));
    }];
    
    //获取盘盈原因
    [_bridge registerHandler:@"onGetPYYY" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getPYYYDic]);
    }];
    
    //获取服务器配置信息
    [_bridge registerHandler:@"getCurrentServerConfig" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getCurrentServerConfig]);
    }];
    
    //保存服务器配置信息
    [_bridge registerHandler:@"changeServerConfig" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        [self changeServerConfig:data];
        responseCallback(@"1");
    }];
    
    //删除本地缓存
    [_bridge registerHandler:@"onClearCache" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self clearCache]));
    }];
    
    //保存Zjb
    [_bridge registerHandler:@"saveZjb" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self saveZjb:data]));
    }];
    
    //获取Zjb
    [_bridge registerHandler:@"getZjb" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback([self getZjb]);
    }];
    
    //删除Zjb
    [_bridge registerHandler:@"deleteZjb" handler:^(id data, WVJBResponseCallback responseCallback) {
        
        responseCallback(@([self deleteZjb:data]));
    }];
    
    [_bridge registerHandler:@"showMessage" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"报告，oc已收到js的请求");
        
        [self JSshowMessage:data];
    }];
    
    [_bridge registerHandler:@"callFoundation" handler:^(id data, WVJBResponseCallback responseCallback) {
        responseCallback(@"报告，oc已收到js的请求");
        
        [self callJSFoundation:data];
    }];
}

//适配JS调用的方法
- (void)JSshowMessage:(NSString *)message
{
    [AITools showAlertWithVC:self title:nil message:message cancelText:@"确定"];
}

//回调JS方法
- (void)callJSFoundation:(NSString *)foundationName
{
    [_bridge callHandler:foundationName data:@{ @"keyFromOC":@"valueFromOC" }];
}


#pragma mark - File
//显示遮罩
- (BOOL)showProgress:(NSString *)str
{
    if (str.length == 0) {
        str = @"正在加载";
    }
    LPCHUDShowMask(str);
    return YES;
}

//隐藏遮罩
- (BOOL)hideProgress
{
    LPCHUDDismiss();
    return YES;
}

//保存登陆信息
- (BOOL)saveLoginJSON:(id)data
{
    [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"AILoginInfo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return YES;
}

//获取登陆信息
- (NSString *)getLoginJSON
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"AILoginInfo"];
}

//获取当前登录单位编号
- (NSString *)getCurrentDepartcode
{
    NSDictionary *dicLoginInfo = [AITools jsonStringToObject:[self getLoginJSON]];
    if (dicLoginInfo && dicLoginInfo[@"userid"] && dicLoginInfo[@"departcode"]) {
        return [NSString stringWithFormat:@"%@%@",dicLoginInfo[@"userid"],dicLoginInfo[@"departcode"]];
    }
    return @"";
}

//查询本地已存在的文件数组
- (NSArray *)fileNamesArrayAtDownload
{
    return [AITools allFileNamesAtPath:PATH_DownloadPath];
}

//查询本地已存在的文件数据数组
- (NSArray *)fileDataArrayAtDownload
{
    //有bug
    NSMutableArray *array = [@[] mutableCopy];
    for (NSString *filePath in [AITools allFilesAtPath:PATH_DownloadPath]) {
        NSData * data = [NSData dataWithContentsOfFile:filePath];
        NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        for (NSDictionary *dic in arrayJson) {
            [array addObject:dic];
        }
    }
    return array;
}

//查询本地已存在的必要数据数组
- (NSString *)onGetNecessaryJSONAtDownload
{
    NSMutableArray *arrayReturn = [@[] mutableCopy];
    for (NSString *filePath in [AITools allFilesAtPath:PATH_DownloadPath]) {
        NSData * data = [NSData dataWithContentsOfFile:filePath];
        NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSMutableDictionary *dicSave = [@{} mutableCopy];
        [dicSave setValue:arrayJson[0][@"planNumber"] forKey:@"planNumber"];
        [dicSave setValue:arrayJson[0][@"planName"] forKey:@"planName"];
        [arrayReturn addObject:dicSave];
    }
    return [AITools objectToJSONString:arrayReturn];
}

//根据plNum查询计划书中的的资产数组
- (NSString *)fileDataArrayAtDownloadFile:(NSString *)planNum
{
    NSString *filePath = [PATH_DownloadPath stringByAppendingPathComponent:planNum];
    NSData * data = [NSData dataWithContentsOfFile:filePath];
    NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    return [AITools objectToJSONString:arrayJson];
}

//保存单个公司的盘点详细数据
- (void)saveDetailJSON:(id)data handler:(WVJBResponseCallback)responseCallback
{
    id jsonDic = [AITools jsonStringToObject:data];
    NSDictionary *dataDic = @{};
    if ([jsonDic isKindOfClass:[NSArray class]]) {
        if ([jsonDic count] == 0) {
            [LPCMBProgressHUD showErrorWithText:@"保存失败：资产数量为0"];
            responseCallback(@(NO));
            return;
        }else {
            dataDic = jsonDic[0];
        }
    }
    else if ([jsonDic isKindOfClass:[NSDictionary class]]) {
        
    }
    
    //删除盘点数据
    [AITools removeAllFilesAtPath:PATH_DownloadPath];
    //删除待提交数据
    [self cleanTobesubmit];
    NSString *fileName = [NSString stringWithFormat:@"%@",dataDic[@"planNumber"]];
    if ([AITools saveFileWithFileName:fileName data:jsonDic folderPath:PATH_DownloadPath]) {
        [LPCMBProgressHUD showSuccessWithText:@"下载成功"];
        responseCallback(@(YES));
    }else {
        responseCallback(@(NO));
    }
}

//保存单个公司的必要盘点数据
- (void)saveNecessaryDetailJSON:(id)data handler:(WVJBResponseCallback)responseCallback
{
    id jsonDic = [AITools jsonStringToObject:data];
    NSDictionary *dataDic = @{};
    NSMutableArray *arraySave = [@[] mutableCopy];
    if ([jsonDic isKindOfClass:[NSArray class]]) {
        dataDic = jsonDic[0];
        for (NSDictionary *dicDetail in jsonDic) {
            NSMutableDictionary *dicSave = [@{} mutableCopy];
            [dicSave setValue:dicDetail[@"assetsCode"] forKey:@"assetsCode"];
            [dicSave setValue:dicDetail[@"assetsName"] forKey:@"assetsName"];
            [dicSave setValue:dicDetail[@"planNumber"] forKey:@"planNumber"];
            [dicSave setValue:dicDetail[@"planName"] forKey:@"planName"];
            [arraySave addObject:dicSave];
        }
    }
    else if ([jsonDic isKindOfClass:[NSDictionary class]]) {
        
    }
    NSString *fileName = [NSString stringWithFormat:@"%@",dataDic[@"planNumber"]];
    if ([AITools saveFileWithFileName:fileName data:arraySave folderPath:PATH_DownloadPath]) {
        [LPCMBProgressHUD showSuccessWithText:@"下载成功"];
        responseCallback(@(YES));
    }else {
        responseCallback(@(NO));
    }
}

//根据id查询指定设备的详细数据
- (id)getJSONWithDeviceId:(id)deviceIdObject //NSString、NSNumber
{
    NSString *deviceId = [NSString stringWithFormat:@"%@",deviceIdObject]; //保证即使传过来的是NSNumber也能保证稳定
    NSAssert(deviceId != nil, @"deviceId 为 nil");
    for (NSString *filePath in [AITools allFilesAtPath:PATH_DownloadPath]) {
        NSData * data = [NSData dataWithContentsOfFile:filePath];
        NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        for (NSDictionary *dicDevice in arrayJson) {
            if ([[NSString stringWithFormat:@"%@",dicDevice[@"barCode"]] isEqualToString:deviceId]) {
                return [AITools objectToJSONString:dicDevice];
            }
        }
    }
//    [LPCMBProgressHUD showErrorWithText:@"查询不到数据"];
    return [AITools objectToJSONString:@{@"QRCodeLPC":deviceId}];
}

//保存待提交的盘点申请到本地
- (BOOL)saveTobesubmitArray:(NSDictionary *)data
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[AITools jsonStringToObject:[self getTobesubmitArray]]];
    NSAssert(data != nil, @"data 为 nil");
    if (data == nil) {
        [LPCMBProgressHUD showErrorWithText:@"保存失败"];
        return NO;
    }else {
        data = [AITools jsonStringToObject:(NSString *)data];
    }
    if (![array containsObject:data]) { //保证没有重复保存
        if (array.count == 0) {
            [array addObject:[AITools objectToJSONString:data]];
        }else {
            BOOL isExist = NO;
            for (int i = 0; i < array.count; i++) {
                NSDictionary *dic = [AITools jsonStringToObject:array[i]];
                if ([[NSString stringWithFormat:@"%@",dic[@"barCode"]] isEqualToString:[NSString stringWithFormat:@"%@",data[@"barCode"]]]) {
                    isExist = YES;
                    [array replaceObjectAtIndex:i withObject:[AITools objectToJSONString:data]];
                }
            }
            if (!isExist) {
                [array addObject:[AITools objectToJSONString:data]];
            }
        }
    }
    
    //盘点状态覆盖本地下载数据
    NSString *filePath = [PATH_DownloadPath stringByAppendingPathComponent:[self fileNamesArrayAtDownload][0]];
    NSData * dataDownload = [NSData dataWithContentsOfFile:filePath];
    NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:dataDownload];
    NSMutableArray *arraySave = [arrayJson mutableCopy];
    NSString *fileName = [self fileNamesArrayAtDownload][0];
    BOOL isExist = NO;
    for (NSDictionary *dicDevice in arrayJson) {
        if ([[NSString stringWithFormat:@"%@",dicDevice[@"barCode"]] isEqualToString:[NSString stringWithFormat:@"%@",data[@"barCode"]]]) {
            isExist = YES;
            [arraySave replaceObjectAtIndex:[arrayJson indexOfObject:dicDevice] withObject:data];
        }
    }
    //如果记录中不存在证明是新增的盘盈数据
    if (!isExist) {
        [arraySave addObject:data];
    }
    [AITools saveFileWithFileName:fileName data:arraySave folderPath:PATH_DownloadPath];
    //保存待提交的盘点申请
    NSData * dataData = [NSKeyedArchiver archivedDataWithRootObject:array];
    BOOL success = [dataData writeToFile:PATH_TobesubmitListPath atomically:YES];
    return success;
}

//获取待提交的盘点申请列表
- (NSString *)getTobesubmitArray
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *strReturn = [AITools objectToJSONString:[NSKeyedUnarchiver unarchiveObjectWithFile:PATH_TobesubmitListPath]];
    return strReturn;
}

//获取待提交的盘点申请单位列表
- (NSString *)getTobesubmitDepartArray
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSArray *arrayInventory = [NSArray arrayWithContentsOfFile:PATH_TobesubmitListPath];
    NSMutableArray *arrayDeparts = [@[] mutableCopy];
    for (NSDictionary *dicInventory in arrayInventory) {
        if (![arrayDeparts containsObject:dicInventory[@"departName"]]) {
            [arrayDeparts addObject:dicInventory[@"departName"]];
        }
    }
    return [AITools objectToJSONString:arrayDeparts];
}

//删除对应的待提交盘点数据
- (void)deleteTobesubmitWithBarcode:(NSString *)barcode
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[AITools jsonStringToObject:[self getTobesubmitArray]]];
    
    for (NSString *dicJSONStr in array.reverseObjectEnumerator) {
        NSDictionary *dic = [AITools jsonStringToObject:dicJSONStr];
        if ([[NSString stringWithFormat:@"%@",dic[@"barCode"]] isEqualToString:barcode]) {
            [array removeObject:dicJSONStr];
        }
    }
    
    //都删除干净了
    if (array.count == 0) {
        [self cleanTobesubmit];
    }else {
        //保存剩余的待提交的盘点申请
        NSData * dataData = [NSKeyedArchiver archivedDataWithRootObject:array];
        [dataData writeToFile:PATH_TobesubmitListPath atomically:YES];
    }
}

//清空待提交的盘点申请列表
- (void)cleanTobesubmit
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:PATH_TobesubmitListPath]) {
       [fm removeItemAtPath:PATH_TobesubmitListPath error:nil];
    }
}

//保存报废列表
- (BOOL)saveScrapList:(NSDictionary *)data
{
    NSMutableArray *array = [[NSMutableArray alloc] initWithArray:[AITools jsonStringToObject:[self getScrapList]]];
    NSAssert(data != nil, @"data 为 nil");
    if (data == nil) {
        [LPCMBProgressHUD showErrorWithText:@"保存失败"];
        return NO;
    }
    if (![array containsObject:data]) { //保证没有重复保存
        [array addObject:data];
    }
    return [array writeToFile:PATH_ScrapListPath atomically:YES];
}

//将报废信息加入报废列表
- (BOOL)addToScrapList:(NSString *)data
{
    NSMutableArray *arrayScrap = [[NSArray arrayWithContentsOfFile:PATH_ScrapListPath] mutableCopy];
    if (!arrayScrap) {
        arrayScrap = [@[] mutableCopy];
    }
    /*
    for (NSString *strDic in arrayScrap.reverseObjectEnumerator) {
        NSDictionary *dic = [AITools jsonStringToObject:strDic];
        if ([dic[@"eamDiscardInvoices"][@"phoneInvoiceNumber"] isEqualToString:[AITools jsonStringToObject:data][@"eamDiscardInvoices"][@"phoneInvoiceNumber"]]) {
            [arrayScrap replaceObjectAtIndex:[arrayScrap indexOfObject:strDic] withObject:data];
            return [arrayScrap writeToFile:PATH_ScrapListPath atomically:YES];
        }
    }
     */
    [arrayScrap addObject:data];
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [arrayScrap writeToFile:PATH_ScrapListPath atomically:YES];
}

//删除报废列表中的一部分
- (BOOL)removeItemOfScrapList:(NSArray *)arrayRemove
{
    NSMutableArray *arrayScrap = [[NSArray arrayWithContentsOfFile:PATH_ScrapListPath] mutableCopy];
    NSMutableArray *arraySave = [arrayScrap mutableCopy];
    for (NSString *strDicRemove in arrayRemove) {
        NSDictionary *dic = [AITools jsonStringToObject:strDicRemove];
        for (NSString *strDic in arrayScrap) {
            NSDictionary *dicSave = [AITools jsonStringToObject:strDic];
            if ([dicSave[@"eamDiscardInvoices"][@"barCode"] isEqualToString:dic[@"eamDiscardInvoices"][@"barCode"]]) {
                [arraySave removeObject:strDic];
            }
        }
    }
    return [arraySave writeToFile:PATH_ScrapListPath atomically:YES];
}

//获取报废列表
- (NSString *)getScrapList
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSMutableArray *arraySave = [@[] mutableCopy];
    for (NSString *str in [NSArray arrayWithContentsOfFile:PATH_ScrapListPath]) {
        [arraySave addObject:[AITools jsonStringToObject:str]];
    }
    NSString *strReturn = [AITools objectToJSONString:arraySave];
    return strReturn;
}

//清除报废列表
- (BOOL)clearScrapList
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:PATH_ScrapListPath]) {
        [fm removeItemAtPath:PATH_ScrapListPath error:nil];
    }
    return YES;
}

//根据departCode获取设备列表
- (NSString *)findDevicesByDepartCode:(NSString *)dicStr
{
    NSDictionary *dic = [AITools jsonStringToObject:dicStr];
    NSString *deviceId = [NSString stringWithFormat:@"%@",dic[@"departCode"]]; //保证即使传过来的事NSNumber也能保证稳定
    NSAssert(deviceId != nil, @"deviceId 为 nil");
    NSMutableArray *arrayReturn = [@[] mutableCopy];
    for (NSString *filePath in [AITools allFilesAtPath:PATH_DownloadPath]) {
        NSData * data = [NSData dataWithContentsOfFile:filePath];
        NSArray *arrayJson = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        
        for (NSDictionary *dicDevice in arrayJson) {
            //未盘点
            if ([[dic objectForKey:@"checkResult"] isEqual:[NSNull null]]) {
                if ([[NSString stringWithFormat:@"%@",dicDevice[@"departCode"]] isEqualToString:deviceId] &&
                    [[dicDevice objectForKey:@"checkResult"] isEqual:[NSNull null]]) {
                    [arrayReturn addObject:dicDevice];
                }
            }else {
                //全部
                if ([@"100" isEqualToString:dic[@"checkResult"]]) {
                    if ([[NSString stringWithFormat:@"%@",dicDevice[@"departCode"]] isEqualToString:deviceId]) {
                        [arrayReturn addObject:dicDevice];
                    }
                }else {
                    if ([[NSString stringWithFormat:@"%@",dicDevice[@"departCode"]] isEqualToString:deviceId] &&
                        [[NSString stringWithFormat:@"%@",dicDevice[@"checkResult"]] isEqualToString:dic[@"checkResult"]]) {
                        [arrayReturn addObject:dicDevice];
                    }
                }
            }
        }
    }
    return [AITools objectToJSONString:arrayReturn];
}

//保存覆盖新的单位列表
- (BOOL)onSaveDeparts:(NSString *)data
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    BOOL isSuccess = [data writeToFile:PATH_DepartsPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
     return isSuccess;
}

//获取调出单位列表
- (NSMutableArray *)getSetInDeparts:(NSString *)departCode
{
    NSMutableArray *arrayReturn = [@[] mutableCopy];
    NSArray *arrayLocalDeparts = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:PATH_DepartsPath]) {
        arrayLocalDeparts = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:PATH_DepartsPath encoding:NSUTF8StringEncoding error:nil]];
    }else {
        arrayLocalDeparts = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InvoiceDeparts" ofType:@"json"] encoding:NSUTF8StringEncoding error:nil]];
    }
    NSDictionary *loginDic = [AITools jsonStringToObject:[self getLoginJSON]];
    for (NSDictionary *dic in arrayLocalDeparts) {
        if ([dic[@"departcode"] hasPrefix:departCode]) {
            if ([loginDic[@"departcode"] isEqualToString:dic[@"departcode"]]) {
                [arrayReturn insertObject:dic atIndex:0];
            }else {
                [arrayReturn addObject:dic];
            }
        }
    }
    return arrayReturn;
}

//获取所有明细单位列表
- (NSMutableArray *)getSetOutDeparts
{
    NSMutableArray *arrayReturn = [@[] mutableCopy];
    NSArray *arrayLocalDeparts = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:PATH_DepartsPath]) {
        arrayLocalDeparts = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:PATH_DepartsPath encoding:NSUTF8StringEncoding error:nil]];
    }else {
        arrayLocalDeparts = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"InvoiceDeparts" ofType:@"json"] encoding:NSUTF8StringEncoding error:nil]];
    }
    for (NSDictionary *dic in arrayLocalDeparts) {
        if ([[NSString stringWithFormat:@"%@",dic[@"marktail"]] isEqualToString:@"1"]) {
            [arrayReturn addObject:dic];
        }
    }
    return arrayReturn;
}

//保存覆盖新的存放地点
- (BOOL)onSaveCFDD:(NSString *)data
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [data writeToFile:PATH_CFDD atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

//获取存放地点
- (NSMutableArray *)getCFDDDic
{
    NSMutableArray *arrayReturn = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if ([fm fileExistsAtPath:PATH_CFDD]) {
        arrayReturn = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:PATH_CFDD encoding:NSUTF8StringEncoding error:nil]];
    }
    return arrayReturn;
}

//保存覆盖新的盘盈原因字典
- (BOOL)onSavePYYY:(NSString *)data
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [data writeToFile:PATH_PYYY atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

//获取盘盈原因
- (NSMutableArray *)getPYYYDic
{
    NSMutableArray *arrayReturn = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if ([fm fileExistsAtPath:PATH_PYYY]) {
        arrayReturn = [AITools jsonStringToObject:[NSString stringWithContentsOfFile:PATH_PYYY encoding:NSUTF8StringEncoding error:nil]];
    }
    return arrayReturn;
}

//保存单位列表
- (BOOL)saveDepartList:(NSDictionary *)data
{
    NSAssert(data != nil, @"data 为 nil");
    if (data == nil) {
        [LPCMBProgressHUD showErrorWithText:@"保存失败"];
        return NO;
    }
    return [data writeToFile:PATH_DepartListPath atomically:YES];
}

//获取单位列表
- (NSString *)getDepartList
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [AITools objectToJSONString:[NSDictionary dictionaryWithContentsOfFile:PATH_DepartListPath]];
}

//保存单位列表
- (BOOL)saveDepartList2:(NSDictionary *)data
{
    NSAssert(data != nil, @"data 为 nil");
    if (data == nil) {
        [LPCMBProgressHUD showErrorWithText:@"保存失败"];
        return NO;
    }
    return [data writeToFile:PATH_DepartListPath2 atomically:YES];
}

//获取单位列表
- (NSString *)getDepartList2
{
    NSFileManager *fm = [NSFileManager defaultManager];
    //如果路径文件夹不存在 创建路径文件夹
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [AITools objectToJSONString:[NSDictionary dictionaryWithContentsOfFile:PATH_DepartListPath2]];
}

//保存待提交的盘点申请到本地
- (BOOL)saveZjb:(NSDictionary *)dic
{
    if (dic == nil) {
        [LPCMBProgressHUD showErrorWithText:@"保存失败"];
        return NO;
    }
    NSString *fileName = dic[@"uploadTableName"];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (![fm fileExistsAtPath:PATH_LocalSavePath]) {
        [fm createDirectoryAtPath:PATH_LocalSavePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (![fm fileExistsAtPath:PATH_ZjbListPath]) {
        [fm createDirectoryAtPath:PATH_ZjbListPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    BOOL success = [dic writeToFile:[PATH_ZjbListPath stringByAppendingPathComponent:fileName] atomically:YES];
    return success;
}

//获取待提交的盘点申请列表
- (NSString *)getZjb
{
    NSArray *arrayFileNames = [AITools allFileNamesAtPath:PATH_ZjbListPath];
    NSMutableArray *arrayReturn = [@[] mutableCopy];
    for (NSString *fileName in arrayFileNames) {
        NSString *filePath = [PATH_ZjbListPath stringByAppendingPathComponent:fileName];
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filePath];
        [arrayReturn addObject:dic];
    }
    return [AITools objectToJSONString:arrayReturn];
}

//删除Zjb
- (BOOL)deleteZjb:(NSString *)zjbDicStr
{
    NSString *filePath = [PATH_ZjbListPath stringByAppendingPathComponent:zjbDicStr];
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:filePath]) {
        return [fm removeItemAtPath:filePath error:nil];
    }
    return YES;
}

//获取服务器配置信息
- (id)getCurrentServerConfig
{
    return [[NSUserDefaults standardUserDefaults] objectForKey:@"AIServerConfig"];
}

//保存服务器配置信息
- (void)changeServerConfig:(NSString *)arrayStr
{
    [[NSUserDefaults standardUserDefaults] setObject:arrayStr forKey:@"AIServerConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

//清除缓存
- (BOOL)clearCache
{
    [self cleanCacheAndCookie];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"AIServerConfig"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"AILoginInfo"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    for (NSString *fileName in [[NSFileManager defaultManager] enumeratorAtPath:PATH_Document]) {
        [[NSFileManager defaultManager] removeItemAtPath:[PATH_Document stringByAppendingPathComponent:fileName] error:nil];
    }
    return YES;
}

//清除缓存和cookie
- (void)cleanCacheAndCookie
{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}


#pragma mark - Custom
//WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
//    NSLog(@"是否允许这个导航");
    decisionHandler(WKNavigationActionPolicyAllow);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
//    NSLog(@"知道返回内容之后，是否允许加载，允许加载");
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
//    NSLog(@"开始加载");
    GCD_ONCE(^{
        [self showProgress:nil];
    });
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
//    NSLog(@"跳转到其他的服务器");
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
//    NSLog(@"网页由于某些原因加载失败");
    [self hideProgress];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation
{
//    NSLog(@"网页开始接收网页内容");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
//    NSLog(@"网页导航加载完毕");
    [self hideProgress];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    self.title = webView.title;
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable ss, NSError * _Nullable error) {
//        NSLog(@"----document.title:%@---webView title:%@",ss,webView.title);
    }];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
//    NSLog(@"加载失败,失败原因:%@",[error description]);
    [self hideProgress];
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
//    NSLog(@"网页加载内容进程终止");
    [self hideProgress];
}

#pragma mark - javascript alert 不弹的解决方案
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self hideProgress];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self hideProgress];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self hideProgress];
    [self presentViewController:alertController animated:YES completion:nil];
}


@end

